package net.zhuike.novel.app.ui.fragment;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.luomi.lm.ad.ADType;
import com.luomi.lm.ad.DRAgent;
import com.luomi.lm.ad.IAdSuccessBack;
import com.umeng.analytics.MobclickAgent;

import net.zhuike.novel.app.R;
import net.zhuike.novel.app.RxBus;
import net.zhuike.novel.app.ZhuiKeApplication;
import net.zhuike.novel.app.bean.BookChapterBean;
import net.zhuike.novel.app.bean.BookMixAToc;
import net.zhuike.novel.app.bean.BookSit;
import net.zhuike.novel.app.bean.ChapterInfoBean;
import net.zhuike.novel.app.bean.CollBookBean;
import net.zhuike.novel.app.bean.DownloadTaskBean;
import net.zhuike.novel.app.bean.Recommend;
import net.zhuike.novel.app.bean.RecommendBookPackage;
import net.zhuike.novel.app.bean.SitBean;
import net.zhuike.novel.app.bean.local.BookRepository;
import net.zhuike.novel.app.bean.local.ReadSettingManager;
import net.zhuike.novel.app.bean.local.SitRepository;
import net.zhuike.novel.app.bean.support.DownloadMessage;
import net.zhuike.novel.app.bean.support.RefreshCollectionIconEvent;
import net.zhuike.novel.app.bean.support.RefreshCollectionListEvent;
import net.zhuike.novel.app.bean.support.UserSexChooseFinishedEvent;
import net.zhuike.novel.app.event.DeleteTaskEvent;
import net.zhuike.novel.app.event.RecommendBookEvent;
import net.zhuike.novel.app.manager.CacheManager;
import net.zhuike.novel.app.manager.CollectionsManager;
import net.zhuike.novel.app.manager.EventManager;
import net.zhuike.novel.app.manager.SettingManager;
import net.zhuike.novel.app.service.BookReadService;
import net.zhuike.novel.app.service.BookShelfService;
import net.zhuike.novel.app.ui.activity.BookDetailActivity;
import net.zhuike.novel.app.ui.activity.MainActivity;
import net.zhuike.novel.app.ui.activity.ReadActivity;
import net.zhuike.novel.app.ui.activity.SearchActivity;
import net.zhuike.novel.app.ui.adapter.RecommendGirdAdapter;
import net.zhuike.novel.app.ui.adapter.TocListAdapter;
import net.zhuike.novel.app.ui.base.BaseFragment;
import net.zhuike.novel.app.ui.adapter.RecommendAdapter;
import net.zhuike.novel.app.ui.base.Constant;
import net.zhuike.novel.app.ui.utils.FormatUtils;
import net.zhuike.novel.app.ui.utils.RxUtils;
import net.zhuike.novel.app.ui.utils.SharedPreferencesUtil;
import net.zhuike.novel.app.ui.utils.SiteHelper;
import net.zhuike.novel.app.ui.utils.StringUtils;
import net.zhuike.novel.app.ui.utils.ToastUtils;
import net.zhuike.novel.app.ui.view.SupportGridItemDecoration;
import net.zhuike.novel.app.ui.view.UeDialog;
import net.zhuike.novel.app.ui.view.page.TxtChapter;
import net.zhuike.novel.app.ui.view.readview.GenderPopupWindow;
import net.zhuike.novel.app.ui.view.recyclerview.EasyRecyclerView;
import net.zhuike.novel.app.ui.view.recyclerview.adapter.OnLoadMoreListener;
import net.zhuike.novel.app.ui.view.recyclerview.adapter.RecyclerArrayAdapter;
import net.zhuike.novel.app.ui.view.recyclerview.swipe.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.text.SimpleDateFormat;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import framework.common.zanetwork.UeHttpUrl;
import framework.common.zanetwork.core.ResponseCallback;
import framework.log.LogUtils;
import io.reactivex.Single;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import rx.Observable;
import rx.functions.Action1;

/**
 * Created by wq on 2017/6/10.
 * 书架
 */
public class BookShelfFragment extends Fragment implements View.OnClickListener, RecyclerArrayAdapter.OnItemLongClickListener, OnLoadMoreListener, OnRefreshListener, RecyclerArrayAdapter.OnItemClickListener {
    EasyRecyclerView gridViewShlef;
    ImageView compositionBtn;
    ImageView goSearchBtn;
    EasyRecyclerView mRecyclerView;
    RelativeLayout showReadHistory, shlf_top;
    LinearLayout noReadTips;
    LinearLayout goonRead;
    ImageView imgRecommendCover,closeAd;
    TextView bookTitle;
    TextView bookAuster;
    TextView readTimeUpdate;
    TextView bookState;
    TextView readBook;
    ProgressBar numPb;
    RelativeLayout addLayout;
    LinearLayout llBatchManagement, no_shelf_book;
    protected RecyclerArrayAdapter<CollBookBean> mAdapter;
    private RecyclerArrayAdapter<CollBookBean> recommendGirdAdapter;
    private boolean isSelectAll = false;
    private List<CollBookBean> chaptersList = new ArrayList<>();
    private List<BookSit.Chapters> mChapterSitList = new ArrayList<>();
    private Context context;
    private int showView = 0;
    protected int start = 0;
    protected int limit = 20;
    private OkHttpClient mOkHttpClient;

    protected CompositeDisposable mDisposable;

    private SiteHelper helper;
    private ProgressDialog mProgressDialog, pro;
    private Handler handler = null;

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_shelf, container, false);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }

    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
    }

    public void initView() {
        context = getActivity();
        handler = new Handler();
        EventBus.getDefault().register(this);
        gridViewShlef = (EasyRecyclerView) getActivity().findViewById(R.id.gridViewShlef);
        compositionBtn = (ImageView) getActivity().findViewById(R.id.compositionBtn);
        goSearchBtn = (ImageView) getActivity().findViewById(R.id.right);
        mRecyclerView = (EasyRecyclerView) getActivity().findViewById(R.id.recycler_view);
        showReadHistory = (RelativeLayout) getActivity().findViewById(R.id.showReadHistory);
        shlf_top = (RelativeLayout) getActivity().findViewById(R.id.shlf_top);
        noReadTips = (LinearLayout) getActivity().findViewById(R.id.noReadTips);
        goonRead = (LinearLayout) getActivity().findViewById(R.id.goonRead);
        imgRecommendCover = (ImageView) getActivity().findViewById(R.id.imgRecommendCover);
        bookTitle = (TextView) getActivity().findViewById(R.id.bookTitle);
        bookAuster = (TextView) getActivity().findViewById(R.id.bookAuster);
        readTimeUpdate = (TextView) getActivity().findViewById(R.id.readTimeUpdate);
        bookState = (TextView) getActivity().findViewById(R.id.bookState);
        readBook = (TextView) getActivity().findViewById(R.id.readBook);
        numPb = (ProgressBar) getActivity().findViewById(R.id.numPb);
        llBatchManagement = (LinearLayout) getActivity().findViewById(R.id.llBatchManagement);
        no_shelf_book = (LinearLayout) getActivity().findViewById(R.id.no_shelf_book);
        compositionBtn.setOnClickListener(this);
        goSearchBtn.setOnClickListener(this);
        goonRead.setOnClickListener(this);
        configViews();

    }

    public void configViews() {
        initAdapters(RecommendGirdAdapter.class, true, false);
        initAdapter(RecommendAdapter.class, true, false);
        mAdapter.setOnItemLongClickListener(this);
        mAdapter.setOnItemClickListener(this);
        recommendGirdAdapter.setOnItemLongClickListener(this);
        recommendGirdAdapter.setOnItemClickListener(this);
        Disposable donwloadDisp = RxBus.getInstance()
                .toObservable(DownloadMessage.class)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                        event -> {
                            //使用Toast提示
                            ToastUtils.showToast(event.message);
                        }
                );
        if (mDisposable == null) {
            mDisposable = new CompositeDisposable();
        }
        mDisposable.add(donwloadDisp);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.compositionBtn:
                if (showView == 0) {
                    showView = 1;
                    compositionBtn.setImageResource(R.mipmap.gird_img);
                    gridViewShlef.setVisibility(View.GONE);
                    mRecyclerView.setVisibility(View.VISIBLE);
                } else {
                    showView = 0;
                    compositionBtn.setImageResource(R.mipmap.ic_composition_btn);
                    gridViewShlef.setVisibility(View.VISIBLE);
                    mRecyclerView.setVisibility(View.GONE);
                }
                break;
            case R.id.right:
                startActivity(new Intent(getActivity(), SearchActivity.class));
                break;
            case R.id.goonRead:
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String sDateTime = sdf.format(new Date());
                SharedPreferencesUtil.getInstance().putString("readTime", sDateTime);
                CollBookBean recommendBooksBean = BookRepository.getInstance().getCollBook(SharedPreferencesUtil.getInstance().getString(Constant.BOOKID));
                Intent intent = new Intent(getActivity(), ReadActivity.class);
                intent.putExtra("recommendBooksBean", recommendBooksBean);
                intent.putExtra("aid", recommendBooksBean.getAid() + "");
                intent.putExtra(ReadActivity.INTENT_SD, true);
                startActivity(intent);
                break;
        }

    }


    @Override
    public void onResume() {
        super.onResume();
        mRecyclerView.setRefreshing(false);
        gridViewShlef.setRefreshing(false);
        if (!(SettingManager.getInstance().getUserChooseSex() == null || SettingManager.getInstance().getUserChooseSex().equals(""))) {
            gone(llBatchManagement);
            if (SharedPreferencesUtil.getInstance().getString(Constant.BOOKID) != null) {
                showReadHistory.setVisibility(View.VISIBLE);
                noReadTips.setVisibility(View.GONE);
                updateShelfReadBook(SharedPreferencesUtil.getInstance().getString(Constant.BOOKID));
            } else {
                noReadTips.setVisibility(View.VISIBLE);
                showReadHistory.setVisibility(View.GONE);
            }
        }
        MobclickAgent.onPageStart("书架");
        MobclickAgent.onResume(context);
        onRefreshs();
    }
    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("书架");
        MobclickAgent.onPause(context);
    }
    public void onRefreshs() {
        handler.post(runnableUi);

    }

    Runnable runnableUi = new Runnable() {
        @Override
        public void run() {
            //更新界面

            List<CollBookBean> data = BookRepository.getInstance().getCollBooks();
            if (data != null) {
                recommendGirdAdapter.clear();
                recommendGirdAdapter.addAll(data);
                recommendGirdAdapter.notifyDataSetChanged();
                mAdapter.clear();
                mAdapter.addAll(data);
                //不加下面这句代码会导致，添加本地书籍的时候，部分书籍添加后直接崩溃
                //报错：Scrapped or attached views may not be recycled. isScrap:false isAttached:true
                mAdapter.notifyDataSetChanged();

                no_shelf_book.setVisibility(View.GONE);
            } else {
                no_shelf_book.setVisibility(View.VISIBLE);
            }
            if (recommendGirdAdapter != null) {
                if (recommendGirdAdapter.getAllData() != null && recommendGirdAdapter.getAllData().size() == 0) {
                    getRecommendList();
                }
            }
        }

    };
    Runnable runnableUis = new Runnable() {
        @Override
        public void run() {
            //更新界面
            if (pro != null) {
                pro.dismiss();
            }
            ToastUtils.showToast("未获取到章节目录，请换本书吧");
        }

    };
    Runnable runnableU = new Runnable() {
        @Override
        public void run() {
            //更新界面
            if (mProgressDialog != null) {
                mProgressDialog.dismiss();
            }
            ToastUtils.showToast("加入缓存队列成功");
        }

    };
    Runnable rUi = new Runnable() {
        @Override
        public void run() {
            //更新界面
            if (mProgressDialog != null) {
                mProgressDialog.dismiss();
            }
            if (pro != null) {
                pro.dismiss();
            }
            ToastUtils.showToast("加入队列失败");
        }

    };

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void UserSexChooseFinished(UserSexChooseFinishedEvent event) {
        //首次进入APP，选择性别后，获取推荐列表
        getRecommendList();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    public void getRecommendList() {
        Map<String, Object> params = new HashMap<>();
        params.put("pageNum", "");
        params.put("pageSize", "");
        BookShelfService.getReComment(context, "38886", new ResponseCallback<RecommendBookPackage>() {
            @Override
            public void onSuccess(RecommendBookPackage advertisesModels) {
                if (advertisesModels.getList() != null) {
                    mAdapter.clear();
                    mAdapter.addAll(advertisesModels.getList());
                    //不加下面这句代码会导致，添加本地书籍的时候，部分书籍添加后直接崩溃
                    //报错：Scrapped or attached views may not be recycled. isScrap:false isAttached:true
                    mAdapter.notifyDataSetChanged();
                    recommendGirdAdapter.clear();
                    recommendGirdAdapter.addAll(advertisesModels.getList());
                    recommendGirdAdapter.notifyDataSetChanged();
                    BookRepository.getInstance()
                            .saveCollBooksWithAsync(advertisesModels.getList());
                    onRefreshs();

                }
            }

            @Override
            public void onError(Response response, int errorCode, String errorMsg, Exception e) {
                Toast.makeText(ZhuiKeApplication.getAppContext(), errorMsg, Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void RefreshCollectionList(RefreshCollectionListEvent event) {
        onRefreshs();
    }

    public void updateShelfReadBook(String bookId) {
        if (bookId != null) {
            CollBookBean recommendBooks = BookRepository.getInstance().getCollBook(bookId);
            bookTitle.setText(recommendBooks.getName());
            bookAuster.setText(recommendBooks.getAuthor());
            bookState.setText(recommendBooks.getProgress());
            if (!(SharedPreferencesUtil.getInstance().getString("readTime") == null || SharedPreferencesUtil.getInstance().getString("readTime").equals(""))) {
                readTimeUpdate.setText(SharedPreferencesUtil.getInstance().getString("readTime"));
            }
            String pos = ReadSettingManager.getInstance().getPercent();
            if (pos != null) {
                readBook.setText("已阅读" + pos + "%");
                numPb.setProgress((int) Float.parseFloat(pos));
            } else {
                readBook.setText("已阅读0%");
                numPb.setProgress(0);
            }
            if (recommendBooks.getCover() != null) {
                Glide.with(context).load(recommendBooks.getCover()).placeholder(R.mipmap.cover_default).error(R.mipmap.cover_default)
                        .into(imgRecommendCover);
            }
        }
    }


    @Override
    public void onItemClick(int position) {
        if (isVisible(llBatchManagement)) //批量管理时，屏蔽点击事件
            return;
        if (showView == 1) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String sDateTime = sdf.format(new Date());
            SharedPreferencesUtil.getInstance().putString("readTime", sDateTime);
            CollBookBean beans = mAdapter.getItem(position);
            if (beans.isLocal()) {
                //id表示本地文件的路径
                String path = beans.getId();
                File file = new File(path);
                //判断这个本地文件是否存在
                if (file.exists()) {
                    SharedPreferencesUtil.getInstance().putString(Constant.BOOKID, recommendGirdAdapter.getItem(position).getId());
                    Intent intent = new Intent(getActivity(), ReadActivity.class);
                    intent.putExtra("recommendBooksBean", recommendGirdAdapter.getItem(position));
                    intent.putExtra("aid", "");
                    intent.putExtra(ReadActivity.INTENT_SD, true);
                    startActivity(intent);
                } else {
                    //提示(从目录中移除这个文件)
                    new AlertDialog.Builder(getContext())
                            .setTitle("提示")
                            .setMessage("文件不存在,是否删除")
                            .setPositiveButton("确定",
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            deleteBook(beans);
                                        }
                                    })
                            .setNegativeButton("取消", null)
                            .show();
                }
            } else {
                Disposable disposable = BookRepository.getInstance()
                        .getBookChaptersInRx(beans.getId())
                        .compose(RxUtils::toSimpleSingle)
                        .subscribe(
                                (bookChapterBeen, throwable) -> {
                                    if (bookChapterBeen.size() > 0) {

                                        SharedPreferencesUtil.getInstance().putString(Constant.BOOKID, mAdapter.getItem(position).getId());
                                        Intent intent = new Intent(getActivity(), ReadActivity.class);
                                        intent.putExtra("recommendBooksBean", mAdapter.getItem(position));
                                        intent.putExtra("aid", mAdapter.getItem(position).getAid() + "");
                                        intent.putExtra(ReadActivity.INTENT_SD, true);
                                        startActivity(intent);
                                    } else {
                                        getBookToc(mAdapter.getItem(position));
                                    }
                                }
                        );
                if (mDisposable == null) {
                    mDisposable = new CompositeDisposable();
                }
                mDisposable.add(disposable);
            }
        } else {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String sDateTime = sdf.format(new Date());
            SharedPreferencesUtil.getInstance().putString("readTime", sDateTime);
            CollBookBean beans = recommendGirdAdapter.getItem(position);
            SharedPreferencesUtil.getInstance().putString(Constant.BOOKID, recommendGirdAdapter.getItem(position).getId());
            if (beans.isLocal()) {
                //id表示本地文件的路径
                String path = beans.getId();
                File file = new File(path);
                //判断这个本地文件是否存在
                if (file.exists()) {
                    SharedPreferencesUtil.getInstance().putString(Constant.BOOKID, recommendGirdAdapter.getItem(position).getId());
                    Intent intent = new Intent(getActivity(), ReadActivity.class);
                    intent.putExtra("recommendBooksBean", recommendGirdAdapter.getItem(position));
                    intent.putExtra("aid", "");
                    intent.putExtra(ReadActivity.INTENT_SD, true);
                    startActivity(intent);
                } else {
                    //提示(从目录中移除这个文件)
                    new AlertDialog.Builder(getContext())
                            .setTitle("提示")
                            .setMessage("文件不存在,是否删除")
                            .setPositiveButton("确定",
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            deleteBook(beans);
                                        }
                                    })
                            .setNegativeButton("取消", null)
                            .show();
                }
            } else {
                Disposable disposable = BookRepository.getInstance()
                        .getBookChaptersInRx(beans.getId())
                        .compose(RxUtils::toSimpleSingle)
                        .subscribe(
                                (bookChapterBeen, throwable) -> {
                                    if (bookChapterBeen.size() > 0) {
                                        Intent intent = new Intent(getActivity(), ReadActivity.class);
                                        intent.putExtra("recommendBooksBean", recommendGirdAdapter.getItem(position));
                                        intent.putExtra("aid", recommendGirdAdapter.getItem(position).getAid() + "");
                                        intent.putExtra(ReadActivity.INTENT_SD, true);
                                        startActivity(intent);
                                    } else {
                                        getBookToc(recommendGirdAdapter.getItem(position));
                                    }
                                }
                        );
                if (mDisposable == null) {
                    mDisposable = new CompositeDisposable();
                }
                mDisposable.add(disposable);
            }

        }
    }

    // @Override
    public boolean onItemLongClick(int position) {
        //批量管理时，屏蔽长按事件
        if (isVisible(llBatchManagement)) return false;
        if (showView == 1) {
            openItemDialog(recommendGirdAdapter.getItem(position));
        } else {
            openItemDialog(mAdapter.getItem(position));
        }
        return false;
    }

    protected void initAdapter(boolean refreshable, boolean loadmoreable) {
        if (mRecyclerView != null) {
            mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
            mRecyclerView.setItemDecoration(ContextCompat.getColor(getActivity(), R.color.common_divider_narrow), 1, 0, 0);
            mRecyclerView.setAdapterWithProgress(mAdapter);
        }

        if (mAdapter != null) {
            mAdapter.setOnItemClickListener(this);
            mAdapter.setError(R.layout.common_error_view).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mAdapter.resumeMore();

                }
            });
        }
    }

    protected void initAdapter(Class<? extends RecyclerArrayAdapter<CollBookBean>> clazz, boolean refreshable, boolean loadmoreable) {
        mAdapter = (RecyclerArrayAdapter<CollBookBean>) createInstance(clazz);
        initAdapter(refreshable, loadmoreable);
    }

    protected void initAdapters(Class<? extends RecyclerArrayAdapter<CollBookBean>> clazz, boolean refreshable, boolean loadmoreable) {
        recommendGirdAdapter = (RecyclerArrayAdapter<CollBookBean>) createInstance(clazz);
        initAdapters(refreshable, loadmoreable);
    }

    protected void initAdapters(boolean refreshable, boolean loadmoreable) {
        if (recommendGirdAdapter != null) {
            gridViewShlef.setLayoutManager(new GridLayoutManager(getActivity(), 3));
            gridViewShlef.addItemDecoration(new SupportGridItemDecoration(getActivity()));
            gridViewShlef.setAdapterWithProgress(recommendGirdAdapter);
        }

        if (recommendGirdAdapter != null) {
            recommendGirdAdapter.setOnItemClickListener(this);
            recommendGirdAdapter.setError(R.layout.common_error_view).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    recommendGirdAdapter.resumeMore();

                }
            });
            if (loadmoreable) {
                recommendGirdAdapter.setMore(R.layout.common_more_view, this);
                recommendGirdAdapter.setNoMore(R.layout.common_nomore_view);
            }

        }
    }

    public Object createInstance(Class<?> cls) {
        Object obj;
        try {
            Constructor c1 = cls.getDeclaredConstructor(Context.class);
            c1.setAccessible(true);
            obj = c1.newInstance(context);
        } catch (Exception e) {
            obj = null;
        }
        return obj;
    }

    @Override
    public void onLoadMore() {
    }

    @Override
    public void onRefresh() {
        mRecyclerView.setRefreshing(false);
        gridViewShlef.setRefreshing(false);
    }

    protected void loaddingError() {
        if (mAdapter.getCount() < 1) { // 说明缓存也没有加载，那就显示errorview，如果有缓存，即使刷新失败也不显示error
            mAdapter.clear();
        }
        mAdapter.pauseMore();
        mRecyclerView.setRefreshing(false);
        mRecyclerView.showTipViewAndDelayClose("似乎没有网络哦");
    }

    protected void gone(final View... views) {
        if (views != null && views.length > 0) {
            for (View view : views) {
                if (view != null) {
                    view.setVisibility(View.GONE);
                }
            }
        }
    }

    protected void visible(final View... views) {
        if (views != null && views.length > 0) {
            for (View view : views) {
                if (view != null) {
                    view.setVisibility(View.VISIBLE);
                }
            }
        }

    }

    protected boolean isVisible(View view) {
        return view.getVisibility() == View.VISIBLE;
    }


    private void openItemDialog(CollBookBean collBook) {
        String[] menus;
        if (collBook.isLocal()) {
            menus = getResources().getStringArray(R.array.nb_menu_local_book);
        } else {
            menus = getResources().getStringArray(R.array.nb_menu_net_book);
        }
        AlertDialog collBookDialog = new AlertDialog.Builder(getContext())
                .setTitle(collBook.getName())
                .setAdapter(new ArrayAdapter<String>(getContext(),
                                android.R.layout.simple_list_item_1, menus),
                        (dialog, which) -> onItemMenuClick(menus[which], collBook))
                .setNegativeButton(null, null)
                .setPositiveButton(null, null)
                .create();

        collBookDialog.show();
    }

    private void onItemMenuClick(String which, CollBookBean collBook) {
        switch (which) {
            //缓存
            case "缓存":
                if (collBook.isLocal()) {
                    ToastUtils.showToast("已经缓存过");
                }else {
                    if (mProgressDialog == null) {
                        mProgressDialog = new ProgressDialog(getActivity());
                        mProgressDialog.setTitle("正在加载到下载队列中");
                    }
                    mProgressDialog.show();
                    getBookMixAToc(collBook);
                }
                break;
            //删除
            case "删除":
                deleteBook(collBook);
                break;
            default:
                break;
        }
    }

    /**
     * 默认删除本地文件
     *
     * @param collBook
     */
    private void deleteBook(CollBookBean collBook) {

        new AlertDialog.Builder(getContext())
                .setTitle("删除文件")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        BookRepository.getInstance().deleteCollBook(collBook);
                        BookRepository.getInstance().deleteBookRecord(collBook.getId());
                        //从Adapter中删除
                        mAdapter.remove(collBook);
                        recommendGirdAdapter.remove(collBook);
                        mAdapter.notifyDataSetChanged();
                        recommendGirdAdapter.notifyDataSetChanged();
                        noReadTips.setVisibility(View.VISIBLE);
                        showReadHistory.setVisibility(View.GONE);
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }

    private void downloadBook(CollBookBean collBookBean, String restr) {
        //创建任务
        DownloadTaskBean task = new DownloadTaskBean();
        task.setAid(collBookBean.getAid());
        task.setTaskName(collBookBean.getName());
        task.setBookId(collBookBean.getId());
        task.setBookChapters(collBookBean.getBookChapters());
        task.setLastChapter(collBookBean.getBookChapters().size());
        task.setResr(restr);
        RxBus.getInstance().post(task);
        handler.post(runnableU);

    }

    public void getBookMixAToc(CollBookBean collBook) {
        BookReadService.getBookMixAToc(getActivity(), collBook.getId(), new ResponseCallback<BookSit>() {
            @Override
            public void onSuccess(BookSit mixToc) {
                if (mixToc != null) {
                    List<BookSit.Chapters> list = mixToc.mulus;

                    mChapterSitList.clear();
                    if (list != null) {
                        mChapterSitList.addAll(list);

                        if (mChapterSitList.size() > 0) {
                            loadCance(collBook.getAid(), mChapterSitList.get(0).domain, mChapterSitList.get(0).url, 0, collBook);
                        }else{
                            handler.post(rUi);
                        }

                    }else{
                        handler.post(rUi);
                    }
                }else{
                    handler.post(rUi);
                }
            }

            @Override
            public void onError(Response response, int errorCode, String errorMsg, Exception e) {
                if (mProgressDialog != null) {
                    mProgressDialog.dismiss();
                }
                Toast.makeText(ZhuiKeApplication.getAppContext(), "网络连接不可用", Toast.LENGTH_SHORT).show();
            }
        });
    }



    public void getBookToc(CollBookBean collBook) {
        if (pro == null) {
            pro = new ProgressDialog(getActivity());
            pro.setTitle("正在获取目录...");
        }
        BookReadService.getBookMixAToc(getActivity(), collBook.getId(), new ResponseCallback<BookSit>() {
            @Override
            public void onSuccess(BookSit mixToc) {
                if (mixToc != null) {
                    List<BookSit.Chapters> list = mixToc.mulus;
                    mChapterSitList.clear();
                    pro.show();
                    if (list != null) {
                        mChapterSitList.addAll(list);

                        if (mChapterSitList.size() > 0) {
                            try {
                                mOkHttpClient = new OkHttpClient.Builder()
                                        .connectTimeout(60, TimeUnit.SECONDS)       //设置连接超时
                                        .readTimeout(60, TimeUnit.SECONDS)          //设置读超时
                                        .writeTimeout(60, TimeUnit.SECONDS)          //设置写超时
                                        .retryOnConnectionFailure(true)             //是否自动重连
                                        .build();
                                final Request request = new Request.Builder()
                                        .url(UeHttpUrl.getChapterRead() + mChapterSitList.get(0).domain)
                                        .get()
                                        .build();
                                Call call = mOkHttpClient.newCall(request);
                                call.enqueue(new Callback() {
                                    @Override
                                    public void onFailure(Call call, IOException e) {
                                        handler.post(rUi);
                                    }

                                    @Override
                                    public void onResponse(Call call, Response response) throws IOException {
                                        String str = response.body().string();
                                        String headers[] = null;

                                        try {
                                            com.alibaba.fastjson.JSONObject restr = com.alibaba.fastjson.JSONObject.parseObject(str);
                                            if (restr.get("failed") != null) {
                                                handler.post(runnableUis);
                                            } else {
                                                List<BookChapterBean> mChapterList = new ArrayList<>();
                                                helper = new SiteHelper(restr);
                                                SharedPreferencesUtil.getInstance().putString(collBook.getId()+"source"+0,"0");
                                                Map<String, Object> contexts = new HashMap<String, Object>();
                                                contexts.put("aid", collBook.getAid());
                                                String loadUrls;
                                                if (mChapterSitList.get(0).url.indexOf("https") != -1) {
                                                    loadUrls = mChapterSitList.get(0).url;
                                                } else {
                                                    if (mChapterSitList.get(0).url.indexOf("qidian.com") != -1) {
                                                        loadUrls = mChapterSitList.get(0).url.replace("http", "https");
                                                    } else {
                                                        loadUrls = mChapterSitList.get(0).url;
                                                    }
                                                }
                                                contexts = helper.executeMulu(contexts, loadUrls);
                                                int i = 0;
                                                while (true) {
                                                    Object[] chapters = (Object[]) contexts.get("chapters");
                                                    if (chapters != null) {
                                                        if (pro != null) {
                                                            pro.dismiss();
                                                        }
                                                        for (Object o : chapters) {
                                                            com.alibaba.fastjson.JSONObject cJson = (com.alibaba.fastjson.JSONObject) o;
                                                            if (!cJson.getString("vip").equals("true")) {
                                                                BookChapterBean chapterBean = new BookChapterBean();
                                                                chapterBean.setBookId(collBook.getId());
                                                                chapterBean.setAid(collBook.getAid());
                                                                chapterBean.setLink(cJson.getString("url"));
                                                                chapterBean.setTitle(cJson.getString("name"));
                                                                mChapterList.add(chapterBean);
                                                            }
                                                        }
                                                        i = 0;
                                                        collBook.setBookChapters(mChapterList);
                                                        BookRepository.getInstance()
                                                                .saveBookChaptersWithAsync(mChapterList);
                                                        BookRepository.getInstance()
                                                                .saveCollBook(collBook);
                                                        SitBean sitBean = new SitBean();
                                                        sitBean.setId(collBook.getId());
                                                        sitBean.setUrl(UeHttpUrl.getChapterRead() + mChapterSitList.get(0).domain);
                                                        sitBean.setLoadUrl(mChapterSitList.get(0).url);
                                                        SitRepository.getInstance().saveSit(sitBean);
                                                        SharedPreferencesUtil.getInstance().putString(Constant.BOOKID, collBook.getId());
                                                        Intent intent = new Intent(getActivity(), ReadActivity.class);
                                                        intent.putExtra("recommendBooksBean", collBook);
                                                        intent.putExtra("aid", collBook.getAid() + "");
                                                        intent.putExtra(ReadActivity.INTENT_SD, true);
                                                        startActivity(intent);
                                                        break;
                                                    } else {
                                                        Thread.sleep(1000);
                                                        i++;
                                                    }
                                                    if (i == 5) {
                                                        if (mChapterSitList.size() > 1) {
                                                            if (pro != null) {
                                                                pro.dismiss();
                                                            }
                                                            changeBookToc(collBook);
                                                        } else {
                                                            handler.post(runnableUis);
                                                        }
                                                        break;
                                                    }
                                                }
                                            }
                                        } catch (Exception e1) {
                                            e1.printStackTrace();
                                            handler.post(runnableUis);
                                        }
                                    }
                                });
                            } catch (Exception e) {
                                handler.post(runnableUis);
                            }
                        }

                    }
                }
            }

            @Override
            public void onError(Response response, int errorCode, String errorMsg, Exception e) {
                Toast.makeText(ZhuiKeApplication.getAppContext(), "网络连接不可用", Toast.LENGTH_SHORT).show();
            }
        });


    }


    private void loadCance(String aid, String url, String loadUrl, final int currentChapter, CollBookBean collBook) {

        try {
            mOkHttpClient = new OkHttpClient.Builder()
                    .connectTimeout(60, TimeUnit.SECONDS)       //设置连接超时
                    .readTimeout(60, TimeUnit.SECONDS)          //设置读超时
                    .writeTimeout(60, TimeUnit.SECONDS)          //设置写超时
                    .retryOnConnectionFailure(true)             //是否自动重连
                    .build();
            final Request request = new Request.Builder()
                    .url(UeHttpUrl.getChapterRead() + url)
                    .get()
                    .build();
            Call call = mOkHttpClient.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    if (mProgressDialog != null) {
                        mProgressDialog.dismiss();
                    }
                    LogUtils.d("a", e);
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String str = response.body().string();
                    String headers[] = null;

                    try {
                        com.alibaba.fastjson.JSONObject restr = com.alibaba.fastjson.JSONObject.parseObject(str);
                        if (restr.get("failed") != null) {
                            handler.post(rUi);
                        } else {
                            SharedPreferencesUtil.getInstance().putString(collBook.getId()+"source"+0,"0");
                            Disposable disposable = BookRepository.getInstance()
                                    .getBookChaptersInRx(collBook.getId())
                                    .compose(RxUtils::toSimpleSingle)
                                    .subscribe(
                                            (bookChapterBeen, throwable) -> {
                                                if (bookChapterBeen.size() > 0) {
                                                    downloadBook(collBook, str);
                                                }else{
                                                    getBookTocs(collBook);
                                                }
                                            }
                                    );
                            if (mDisposable == null) {
                                mDisposable = new CompositeDisposable();
                            }
                            mDisposable.add(disposable);


                        }
                    } catch (Exception e1) {
                        if (mProgressDialog != null) {
                            mProgressDialog.dismiss();
                        }
                        e1.printStackTrace();
                    }
                }
            });
        } catch (Exception e) {
            if (mProgressDialog != null) {
                mProgressDialog.dismiss();
            }
        }
    }

    public void changeBookToc(CollBookBean collBook) {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                UeDialog.showprogressDialog(context, "", "正在换源中，请稍后", false);
            }
        }, 100);

        try {
            mOkHttpClient = new OkHttpClient.Builder()
                    .connectTimeout(60, TimeUnit.SECONDS)       //设置连接超时
                    .readTimeout(60, TimeUnit.SECONDS)          //设置读超时
                    .writeTimeout(60, TimeUnit.SECONDS)          //设置写超时
                    .retryOnConnectionFailure(true)             //是否自动重连
                    .build();
            final Request request = new Request.Builder()
                    .url(UeHttpUrl.getChapterRead() + mChapterSitList.get(1).domain)
                    .get()
                    .build();
            Call call = mOkHttpClient.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {

                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String str = response.body().string();
                    String headers[] = null;

                    try {
                        com.alibaba.fastjson.JSONObject restr = com.alibaba.fastjson.JSONObject.parseObject(str);
                        if (restr.get("failed") != null) {
                            UeDialog.hideProgress();
                            handler.post(runnableUis);
                        } else {
                            SharedPreferencesUtil.getInstance().putString(collBook.getId()+"source"+1,"1");
                            List<BookChapterBean> mChapterList = new ArrayList<>();
                            helper = new SiteHelper(restr);
                            Map<String, Object> contexts = new HashMap<String, Object>();
                            contexts.put("aid", collBook.getAid());
                            String loadUrls;
                            if (mChapterSitList.get(1).url.indexOf("https") != -1) {
                                loadUrls = mChapterSitList.get(1).url;
                            } else {
                                if (mChapterSitList.get(1).url.indexOf("qidian.com") != -1) {
                                    loadUrls = mChapterSitList.get(1).url.replace("http", "https");
                                } else {
                                    loadUrls = mChapterSitList.get(1).url;
                                }
                            }
                            contexts = helper.executeMulu(contexts, loadUrls);
                            int i = 0;
                            while (true) {
                                Object[] chapters = (Object[]) contexts.get("chapters");
                                if (chapters != null) {
                                    if (pro != null) {
                                        pro.dismiss();
                                    }
                                    UeDialog.hideProgress();
                                    for (Object o : chapters) {
                                        com.alibaba.fastjson.JSONObject cJson = (com.alibaba.fastjson.JSONObject) o;
                                        if (!cJson.getString("vip").equals("true")) {
                                            BookChapterBean chapterBean = new BookChapterBean();
                                            chapterBean.setBookId(collBook.getId());
                                            chapterBean.setAid(collBook.getAid());
                                            chapterBean.setLink(cJson.getString("url"));
                                            chapterBean.setTitle(cJson.getString("name"));
                                            mChapterList.add(chapterBean);
                                        }
                                    }
                                    i = 0;
                                    collBook.setBookChapters(mChapterList);
                                    BookRepository.getInstance()
                                            .saveBookChaptersWithAsync(mChapterList);
                                    BookRepository.getInstance()
                                            .saveCollBook(collBook);
                                    SitBean sitBean = new SitBean();
                                    sitBean.setId(collBook.getId());
                                    sitBean.setUrl(UeHttpUrl.getChapterRead() + mChapterSitList.get(1).domain);
                                    sitBean.setLoadUrl(mChapterSitList.get(1).url);
                                    SitRepository.getInstance().saveSit(sitBean);
                                    SharedPreferencesUtil.getInstance().putString(Constant.BOOKID, collBook.getId());
                                    Intent intent = new Intent(getActivity(), ReadActivity.class);
                                    intent.putExtra("recommendBooksBean", collBook);
                                    intent.putExtra("aid", collBook.getAid() + "");
                                    intent.putExtra(ReadActivity.INTENT_SD, true);
                                    startActivity(intent);
                                    break;
                                } else {
                                    Thread.sleep(1000);
                                    i++;
                                }
                                if (i == 5) {
                                    UeDialog.hideProgress();
                                    handler.post(runnableUis);
                                    break;
                                }
                            }
                        }
                    } catch (Exception e1) {
                        e1.printStackTrace();
                        handler.post(runnableUis);
                    }
                }
            });
        } catch (Exception e) {
            handler.post(runnableUis);
        }
    }
    public void getBookTocs(CollBookBean collBook) {
        if (pro == null) {
            pro = new ProgressDialog(getActivity());
            pro.setTitle("正在获取目录...");
        }
        BookReadService.getBookMixAToc(getActivity(), collBook.getId(), new ResponseCallback<BookSit>() {
            @Override
            public void onSuccess(BookSit mixToc) {
                if (mixToc != null) {
                    List<BookSit.Chapters> list = mixToc.mulus;
                    mChapterSitList.clear();
                    pro.show();
                    if (list != null) {
                        mChapterSitList.addAll(list);

                        if (mChapterSitList.size() > 0) {
                            try {
                                mOkHttpClient = new OkHttpClient.Builder()
                                        .connectTimeout(60, TimeUnit.SECONDS)       //设置连接超时
                                        .readTimeout(60, TimeUnit.SECONDS)          //设置读超时
                                        .writeTimeout(60, TimeUnit.SECONDS)          //设置写超时
                                        .retryOnConnectionFailure(true)             //是否自动重连
                                        .build();
                                final Request request = new Request.Builder()
                                        .url(UeHttpUrl.getChapterRead() + mChapterSitList.get(0).domain)
                                        .get()
                                        .build();
                                Call call = mOkHttpClient.newCall(request);
                                call.enqueue(new Callback() {
                                    @Override
                                    public void onFailure(Call call, IOException e) {
                                        handler.post(rUi);
                                    }

                                    @Override
                                    public void onResponse(Call call, Response response) throws IOException {
                                        String str = response.body().string();
                                        String headers[] = null;

                                        try {
                                            com.alibaba.fastjson.JSONObject restr = com.alibaba.fastjson.JSONObject.parseObject(str);
                                            if (restr.get("failed") != null) {
                                                handler.post(runnableUis);
                                            } else {
                                                List<BookChapterBean> mChapterList = new ArrayList<>();
                                                helper = new SiteHelper(restr);
                                                SharedPreferencesUtil.getInstance().putString(collBook.getId()+"source"+0,"0");
                                                Map<String, Object> contexts = new HashMap<String, Object>();
                                                contexts.put("aid", collBook.getAid());
                                                String loadUrls;
                                                if (mChapterSitList.get(0).url.indexOf("https") != -1) {
                                                    loadUrls = mChapterSitList.get(0).url;
                                                } else {
                                                    if (mChapterSitList.get(0).url.indexOf("qidian.com") != -1) {
                                                        loadUrls = mChapterSitList.get(0).url.replace("http", "https");
                                                    } else {
                                                        loadUrls = mChapterSitList.get(0).url;
                                                    }
                                                }
                                                contexts = helper.executeMulu(contexts, loadUrls);
                                                int i = 0;
                                                while (true) {
                                                    Object[] chapters = (Object[]) contexts.get("chapters");
                                                    if (chapters != null) {
                                                        if (pro != null) {
                                                            pro.dismiss();
                                                        }
                                                        for (Object o : chapters) {
                                                            com.alibaba.fastjson.JSONObject cJson = (com.alibaba.fastjson.JSONObject) o;
                                                            if (!cJson.getString("vip").equals("true")) {
                                                                BookChapterBean chapterBean = new BookChapterBean();
                                                                chapterBean.setBookId(collBook.getId());
                                                                chapterBean.setAid(collBook.getAid());
                                                                chapterBean.setLink(cJson.getString("url"));
                                                                chapterBean.setTitle(cJson.getString("name"));
                                                                mChapterList.add(chapterBean);
                                                            }
                                                        }
                                                        i = 0;
                                                        collBook.setBookChapters(mChapterList);
                                                        BookRepository.getInstance()
                                                                .saveBookChaptersWithAsync(mChapterList);
                                                        BookRepository.getInstance()
                                                                .saveCollBook(collBook);
                                                        SitBean sitBean = new SitBean();
                                                        sitBean.setId(collBook.getId());
                                                        sitBean.setUrl(UeHttpUrl.getChapterRead() + mChapterSitList.get(0).domain);
                                                        sitBean.setLoadUrl(mChapterSitList.get(0).url);
                                                        SitRepository.getInstance().saveSit(sitBean);
                                                        SharedPreferencesUtil.getInstance().putString(Constant.BOOKID, collBook.getId());
                                                        getBookMixAToc(collBook);
                                                        break;
                                                    } else {
                                                        Thread.sleep(1000);
                                                        i++;
                                                    }
                                                    if (i == 5) {
                                                        if (mChapterSitList.size() > 1) {
                                                            if (pro != null) {
                                                                pro.dismiss();
                                                            }
                                                            changeBookTocs(collBook);
                                                        } else {
                                                            handler.post(runnableUis);
                                                        }
                                                        break;
                                                    }
                                                }
                                            }
                                        } catch (Exception e1) {
                                            e1.printStackTrace();
                                            handler.post(runnableUis);
                                        }
                                    }
                                });
                            } catch (Exception e) {
                                handler.post(runnableUis);
                            }
                        }

                    }
                }
            }

            @Override
            public void onError(Response response, int errorCode, String errorMsg, Exception e) {
                Toast.makeText(ZhuiKeApplication.getAppContext(), "网络连接不可用", Toast.LENGTH_SHORT).show();
            }
        });


    }

    public void changeBookTocs(CollBookBean collBook) {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                UeDialog.showprogressDialog(context, "", "正在换源中，请稍后", false);
            }
        }, 100);

        try {
            mOkHttpClient = new OkHttpClient.Builder()
                    .connectTimeout(60, TimeUnit.SECONDS)       //设置连接超时
                    .readTimeout(60, TimeUnit.SECONDS)          //设置读超时
                    .writeTimeout(60, TimeUnit.SECONDS)          //设置写超时
                    .retryOnConnectionFailure(true)             //是否自动重连
                    .build();
            final Request request = new Request.Builder()
                    .url(UeHttpUrl.getChapterRead() + mChapterSitList.get(1).domain)
                    .get()
                    .build();
            Call call = mOkHttpClient.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {

                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String str = response.body().string();
                    String headers[] = null;

                    try {
                        com.alibaba.fastjson.JSONObject restr = com.alibaba.fastjson.JSONObject.parseObject(str);
                        if (restr.get("failed") != null) {
                            UeDialog.hideProgress();
                            handler.post(runnableUis);
                        } else {
                            SharedPreferencesUtil.getInstance().putString(collBook.getId()+"source"+1,"1");
                            List<BookChapterBean> mChapterList = new ArrayList<>();
                            helper = new SiteHelper(restr);
                            Map<String, Object> contexts = new HashMap<String, Object>();
                            contexts.put("aid", collBook.getAid());
                            String loadUrls;
                            if (mChapterSitList.get(1).url.indexOf("https") != -1) {
                                loadUrls = mChapterSitList.get(1).url;
                            } else {
                                if (mChapterSitList.get(1).url.indexOf("qidian.com") != -1) {
                                    loadUrls = mChapterSitList.get(1).url.replace("http", "https");
                                } else {
                                    loadUrls = mChapterSitList.get(1).url;
                                }
                            }
                            contexts = helper.executeMulu(contexts, loadUrls);
                            int i = 0;
                            while (true) {
                                Object[] chapters = (Object[]) contexts.get("chapters");
                                if (chapters != null) {
                                    if (pro != null) {
                                        pro.dismiss();
                                    }
                                    UeDialog.hideProgress();
                                    for (Object o : chapters) {
                                        com.alibaba.fastjson.JSONObject cJson = (com.alibaba.fastjson.JSONObject) o;
                                        if (!cJson.getString("vip").equals("true")) {
                                            BookChapterBean chapterBean = new BookChapterBean();
                                            chapterBean.setBookId(collBook.getId());
                                            chapterBean.setAid(collBook.getAid());
                                            chapterBean.setLink(cJson.getString("url"));
                                            chapterBean.setTitle(cJson.getString("name"));
                                            mChapterList.add(chapterBean);
                                        }
                                    }
                                    i = 0;
                                    collBook.setBookChapters(mChapterList);
                                    BookRepository.getInstance()
                                            .saveBookChaptersWithAsync(mChapterList);
                                    BookRepository.getInstance()
                                            .saveCollBook(collBook);
                                    SitBean sitBean = new SitBean();
                                    sitBean.setId(collBook.getId());
                                    sitBean.setUrl(UeHttpUrl.getChapterRead() + mChapterSitList.get(1).domain);
                                    sitBean.setLoadUrl(mChapterSitList.get(1).url);
                                    SitRepository.getInstance().saveSit(sitBean);
                                    SharedPreferencesUtil.getInstance().putString(Constant.BOOKID, collBook.getId());
                                    getBookMixAToc(collBook);
                                    break;
                                } else {
                                    Thread.sleep(1000);
                                    i++;
                                }
                                if (i == 5) {
                                    UeDialog.hideProgress();
                                    handler.post(runnableUis);
                                    break;
                                }
                            }
                        }
                    } catch (Exception e1) {
                        e1.printStackTrace();
                        handler.post(runnableUis);
                    }
                }
            });
        } catch (Exception e) {
            handler.post(runnableUis);
        }
    }
}
